﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mmeller.Net.Decoder
{
    public class CryptoHeader
    {
        private FileHeader header;

        public struct CryptoHeaderValues
        {
            public string mode;
            public int keyLength;
            public int blockSize;
            public byte[] sessionKey;
            public byte[] initialVector;

            public CryptoHeaderValues(string mode,
                int keyLength, int blockSize, 
                byte[] sessionKey, byte[] initialVector)
            {
                this.mode = mode;
                this.keyLength = keyLength;
                this.blockSize = blockSize;
                this.sessionKey = sessionKey;
                this.initialVector = initialVector;
            }
        }

        public CryptoHeader(FileHeader header)
        {
            this.header = header;
        }


        public CryptoHeaderValues getHeader(string pathToFile)
        {
            try
            {
                Dictionary<string, string> fields = this.header.getFields(pathToFile);
                return new CryptoHeaderValues(fields["mode"],
                    int.Parse(fields["keyLenght"]), int.Parse(fields["blockSize"]),
                    System.Text.Encoding.ASCII.GetBytes(fields["sessionKey"]),
                    System.Text.Encoding.ASCII.GetBytes(fields["initialVector"]));
            }
            catch (Exception e)
            {
                throw new Exception("Invalid values" + e.ToString());
            }
        }

        public void createHeader(CryptoHeaderValues headerValues, string pathToFile)
        {
            List<HeaderField> fields = initializeFields(ref headerValues);
            this.header.createHeader(pathToFile, fields);
        }

        private static List<HeaderField> initializeFields(ref CryptoHeaderValues headerValues)
        {
            List<HeaderField> fields = new List<HeaderField>();
            fields.Add(new HeaderField("mode", headerValues.mode));
            fields.Add(new HeaderField("keyLenght", headerValues.keyLength.ToString()));
            fields.Add(new HeaderField("blockSize", headerValues.blockSize.ToString()));
            fields.Add(new HeaderField("sessionKey", System.Text.Encoding.ASCII.GetString(headerValues.sessionKey)));
            fields.Add(new HeaderField("initialVector", System.Text.Encoding.ASCII.GetString(headerValues.initialVector)));
            return fields;
        }
    }
}
